# -*- coding: utf-8 -*-
#图片预处理模块
#注意左右的区别是，左边是靠近屏幕的那一边
##################################
import cv2 as cv
import numpy as np
from math import sqrt,fabs,cos,sin,pi,log10
 
#顶部图片检测框宽高
#boxH_top=280;
#boxW_top=410;
boxH_top=420;
boxW_top=410;
#底部图片检测框宽高
boxH_bottom=320;
boxW_bottom=330;
#左边或者右边检测框宽高
boxH_lr=250;
boxW_lr=250;
#定义的魔方类型，不同类型的魔方预处理不一样
CUBE_TYPE_BLACK=102;
CUBE_TYPE_WHITE=103;

###################贴纸类型魔方的处理方法#########################


def test(value):
	pass


#伽玛矫正，提升图片亮度，不会让亮区过爆
#伽玛值越大，提升的亮度越不明显
def gammaCorrection(img,isAuto=True,threshold=0.6):
	#自动计算伽玛矫正参数
	if isAuto:
		grayROI=cv.cvtColor(img,cv.COLOR_BGR2GRAY);
		mean = np.mean(grayROI);
		gamma = log10(0.5)/log10(mean/255);
		if(gamma<threshold):
			#需要提升的亮度太高时，适当的降低提高的亮度
			gamma=threshold;
	#使用伽玛矫正提升亮度
	gamma_table = [np.power(x / 255.0,gamma) * 255.0 for x in range(256)] ; # 建立映射表
	gamma_table = np.round(np.array(gamma_table)).astype(np.uint8);  # 颜色值为整数
	return cv.LUT(img, gamma_table);

#判断某一个点是否在矩形框中
def isPointInRect(point,rect):
	x,y=point;
	x1,y1,w,h=rect;
	if x>x1 and y>y1 and x<(x1+w) and y<(y1+h):
		return True;
	return False; 

#计算矩形框中心点
def calcRectCenter(rect):
	x,y,w,h=rect;
	return x+w/2,y+h/2;

#找到那些多个矩形框重叠，然后融合成一个
def overlapRectFusion(rects):
	res=[];
	print("=====================");
	print(len(rects));
	removeIndex=[];
	for i in range(len(rects)):
		rect=rects[i];
		#剔除与自己重叠的框
		for j in range(i+1,len(rects)):
			if j in removeIndex:
				continue;
			temp=rects[j];
			#判断中心点是不是在rect中
			if isPointInRect(calcRectCenter(temp),rect):
				#删除这个框，避免之后重复生成
				removeIndex.append(j);
		res.append(rect);
		print(removeIndex);
	return res;

#绘制这些矩形框到img上
def drawRects(img,rects,offsetX=0,offsetY=0):
	for rect in rects:
		x,y,w,h=rect;
		cv.rectangle(img,(x+offsetX, y+offsetY), (x+w+offsetX, y+h+offsetY), (0,0,255), 1);

#按照Y从小到大排列
def sortByY(rects):
	length=len(rects);
	for i in range(length):
		for j in range(i+1,length):
			if rects[j][1]<rects[i][1]:
				temp=rects[i];
				rects[i]=rects[j];
				rects[j]=temp;
	return rects;

#对一行的6个进行排序	
def sortRowByX(rects,start,end):
	for i in range(start,end):
		for j in range(i+1,end):
			if rects[j][0]<rects[i][0]:
				temp=rects[i];
				rects[i]=rects[j];
				rects[j]=temp;
	return rects;

#图片旋转
def imgRoate(img,angle):
	height=img.shape[1];
	width=img.shape[0];
	matRotate = cv.getRotationMatrix2D((height*0.5, width*0.5), -angle, 1);
	return cv.warpAffine(img, matRotate, (height, width));

#粗略提取魔方，获取根据检测框提取中心的一个ROI
def getCenterBoxROI(top,w,h,offsetX=0,offsetY=0,drawBox=True):
	copyTop=np.copy(top);
	#计算检测框的坐标
	cx,cy=top.shape[1]//2+offsetX,top.shape[0]//2+offsetY;
	x1,y1,x2,y2=cx-w//2,cy-h//2,cx+w//2,cy+h//2;
	#提取检测框ROI
	boxROI=copyTop[y1:y2,x1:x2];
	#绘制检测框
	if drawBox:
		cv.rectangle(top, (x1,y1), (x2, y2), (0,0,255), 1);
	return boxROI,x1,y1;

#一个摄像头处理时
#num:第几张图片
#处理背景为黑色时的顶部图片
def handleTopByOne(top,num=1):
	#num=cv.getTrackbarPos("num","test");
	#top=cv.imread("C:/Users/ASUS/Desktop/img/"+str(num)+".jpg");
	#提取检测框ROI
	w,h=460,460;
	boxROI,x1,y1=getCenterBoxROI(top,w,h,5,0,False);
	#return boxROI,1,1;
	#图片锐化,边缘增强
	kernel=np.array([[0,-1,0],[-1,5,-1],[0,-1,0]],np.float32);
	dst=cv.filter2D(boxROI,-1,kernel=kernel);
	#边缘检测
	#minV=cv.getTrackbarPos("min","test");
	#maxV=cv.getTrackbarPos("max","test");
	#canny = cv.Canny(dst,minV,maxV);
	canny=cv.Canny(boxROI,100,144);
	#return canny,1,1;
	cv.imshow("canny",canny);
	#cv.waitKey(0);
	#提取轮廓
	hierarchy,contours,value=cv.findContours(canny,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)    # 输出为三个参数  
	#绘制轮廓
	#cv.drawContours(boxROI,contours,-1,(0,255,0),1);
	#筛选轮廓提取所有魔方块外接矩形
	#cv.imshow("boxROI",boxROI);
	#cv.waitKey(0);
	rects=[];
	for item in contours:
		x,y,w,h=cv.boundingRect(item);
		division=w/h;
		if w*h>2000 and division>=0.25 and w<h:
			rects.append((x,y,w,h));
	#绘制所有的矩形框
	#drawRects(top,rects,x1,y1);
	#return top,1,1;
	#cv.imshow("test",top);
	#cv.waitKey(0);
	#排布魔方块
	#按外接矩形左上角y的大小依次排列
	rects=sortByY(rects);
	#按外接矩形左上角x的大小再次排列,这次只是6个排一次
	rects=sortRowByX(rects,0,6);
	rects=sortRowByX(rects,6,12);
	rects=sortRowByX(rects,12,18);
	#根据rects生成ROI
	blocks=[];
	for rect in rects:
		x,y,w,h=rect;
		roi=boxROI[y:y+h,x:x+w];
		roi=gammaCorrection(roi);
		blocks.append(roi);
	#填到对应得到面里面
	blocks1=[1,1,1,1,1,1,1,1,1];
	blocks2=[1,1,1,1,1,1,1,1,1];
	if num==1:
		#L面
		blocks1[0]=blocks[2];blocks1[1]=blocks[8];blocks1[2]=blocks[14];
		blocks1[3]=blocks[1];blocks1[4]=blocks[7];blocks1[5]=blocks[13];
		blocks1[6]=blocks[0];blocks1[7]=blocks[6];blocks1[8]=blocks[12];
		#U面
		blocks2[0]=blocks[3];blocks2[1]=blocks[4];blocks2[2]=blocks[5];
		blocks2[3]=blocks[9];blocks2[4]=blocks[10];blocks2[5]=blocks[11];
		blocks2[6]=blocks[15];blocks2[7]=blocks[16];blocks2[8]=blocks[17];
	elif num==2:
		#F面
		blocks1[0]=blocks[0];blocks1[1]=blocks[1];blocks1[2]=blocks[2];
		blocks1[3]=blocks[6];blocks1[4]=blocks[7];blocks1[5]=blocks[8];
		blocks1[6]=blocks[12];blocks1[7]=blocks[13];blocks1[8]=blocks[14];
		#R面
		blocks2[0]=blocks[3];blocks2[1]=blocks[4];blocks2[2]=blocks[5];
		blocks2[3]=blocks[9];blocks2[4]=blocks[10];blocks2[5]=blocks[11];
		blocks2[6]=blocks[15];blocks2[7]=blocks[16];blocks2[8]=blocks[17];
	elif num==3:
		#D面
		blocks1[0]=blocks[12];blocks1[1]=blocks[6];blocks1[2]=blocks[0];
		blocks1[3]=blocks[13];blocks1[4]=blocks[7];blocks1[5]=blocks[1];
		blocks1[6]=blocks[14];blocks1[7]=blocks[8];blocks1[8]=blocks[2];
		#B面
		blocks2[0]=blocks[5];blocks2[1]=blocks[11];blocks2[2]=blocks[17];
		blocks2[3]=blocks[4];blocks2[4]=blocks[10];blocks2[5]=blocks[16];
		blocks2[6]=blocks[3];blocks2[7]=blocks[9];blocks2[8]=blocks[15];
	return top,blocks1,blocks2;

'''
cv.namedWindow("test");
cv.createTrackbar("min","test",23,255,test);
cv.createTrackbar("max","test",255,255,test);
cv.createTrackbar("num","test",0,2,test);
while True:
	num=cv.getTrackbarPos("num","test");
	top=cv.imread("C:/Users/ASUS/Desktop/img/"+str(num+1)+".jpg");
	top,blocks1,blocks2=handleTopByOne(top,num+1);
	cv.imshow("test",top);
	cv.waitKey(10);
'''

#预处理顶部摄像头画面(黑色背景魔方)
def handleTopWithBlack(top):
	return handleTopByOne(top,1);

#处理底部图片(黑色背景)
def handleBottomWithBlack(bottom):
	#提取检测框ROI
	boxROI,x1,y1=getCenterBoxROI(bottom,410,400,0,0,False);
	#边缘检测
	minV=cv.getTrackbarPos("min","test");
	maxV=cv.getTrackbarPos("max","test");
	#canny = cv.Canny(boxROI,minV,maxV);
	canny = cv.Canny(boxROI,98,50);
	#cv.imshow("canny",canny);
	#return canny,1,1
	#提取轮廓
	hierarchy,contours,value=cv.findContours(canny,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
	#绘制轮廓		
	#cv.drawContours(boxROI,contours,-1,(0,255,0),1);
	#return boxROI
	#筛选轮廓提取所有魔方块外接矩形
	rects=[];
	for item in contours:
		#area=cv.contourArea(item);
		x,y,w,h=cv.boundingRect(item);
		area=w*h;
		if area>1000 and h>w:
			#提取外接矩形
			  rects.append((x,y,w,h));
	#绘制所有的矩形框
	drawRects(bottom,rects,x1,y1);
	#cv.imshow("boxROI",bottom);
	#cv.waitKey(0);
	#return bottom,1,0;
	#按外接矩形左上角y的大小依次排列
	rects=sortByY(rects);
	#按外接矩形左上角x的大小再次排列,这次只是6个排一次
	rects=sortRowByX(rects,0,6);
	rects=sortRowByX(rects,6,12);
	rects=sortRowByX(rects,12,18);
	#根据rects生成ROI
	blocks=[];
	for rect in rects:
		x,y,w,h=rect;
		roi=boxROI[y:y+h,x:x+w];
		roi=gammaCorrection(roi);
		blocks.append(roi);
	#填到对应得到面里面
	blocksD=[1,1,1,1,1,1,1,1,1];
	blocksR=[1,1,1,1,1,1,1,1,1];
	#D面
	blocksD[0]=blocks[0];blocksD[1]=blocks[1];blocksD[2]=blocks[2];
	blocksD[3]=blocks[6];blocksD[4]=blocks[7];blocksD[5]=blocks[8];
	blocksD[6]=blocks[12];blocksD[7]=blocks[13];blocksD[8]=blocks[14];
	#R面
	blocksR[0]=blocks[5];blocksR[1]=blocks[11];blocksR[2]=blocks[17];
	blocksR[3]=blocks[4];blocksR[4]=blocks[10];blocksR[5]=blocks[16];
	blocksR[6]=blocks[3];blocksR[7]=blocks[9];blocksR[8]=blocks[15];
	return bottom,blocksD,blocksR;

'''
cv.namedWindow("test");
cv.createTrackbar("min","test",23,255,test);
cv.createTrackbar("max","test",138,255,test);
while True:
	img=cv.imread("C:\\Users\\ASUS\\Desktop\\img\\bottom.jpg");
	boxImg,w,wd=handleBottomWithBlack(img);
	cv.imshow("test",boxImg);
	cv.waitKey(10);
'''

#预处理左边摄像头或者右边的画面(黑色背景)
def handleLeftOrRightWithBlack(img,pos="left"):
	#pos为left时的默认值
	roateAngle=-45;
	offsetX=20;
	offsetY=20;
	#纠正图片
	if pos=="right":
		roateAngle=45;
		offsetX=-20;
	roateImg=imgRoate(img,roateAngle);
	#提取检测框ROI
	boxROI,x1,y1=getCenterBoxROI(roateImg,350,320,offsetX,offsetY,False);
	#cv.imshow("boxROI",boxROI);
	#cv.waitKey(0);
	#return boxROI,1;
	#灰度化
	grayROI=cv.cvtColor(boxROI,cv.COLOR_BGR2GRAY);
	#二值化
	#minV=cv.getTrackbarPos("min","test");
	#maxV=cv.getTrackbarPos("max","test");
	canny=cv.Canny(grayROI,23,138);
	#cv.imshow("canny",canny);
	#return canny,1;
	#提取轮廓
	hierarchy,contours,value=cv.findContours(canny,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
	#绘制轮廓
	#cv.drawContours(boxROI,contours,-1,(0,255,0),1);
	#return boxROI,1;
	#轮廓筛选同时提取最小外接矩形
	rects=[];
	for item in contours:
		#计算最小外接矩形
		area=cv.contourArea(item);
		x,y,w,h=cv.boundingRect(item);
		area=w*h;
		if fabs(w-h)<15 and area>4500:
			rects.append((x,y,w,h));	
	#绘制所有的矩形框
	#drawRects(roateImg,rects,x1,y1);
	#return roateImg,1;
	#按照Y排序
	rects=sortByY(rects);
	#按照每一行的X排序
	rects=sortRowByX(rects,0,3);
	rects=sortRowByX(rects,3,6);
	rects=sortRowByX(rects,6,9);
	#根据Rects生成ROI
	blocks=[];
	for rect in rects:
		blocks.append(boxROI[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]);
	return roateImg,blocks;

'''
cv.namedWindow("test");
cv.createTrackbar("min","test",23,255,test);
cv.createTrackbar("max","test",138,255,test);
img=cv.imread("C:/Users/ASUS/Desktop/img/left.jpg");
while True:
	boxImg,blocks=handleLeftOrRightWithBlack(img,"left");
	cv.imshow("test",boxImg);
	cv.waitKey(10);
'''

#处理4个摄像头时的黑色背景的魔方
def handleFourCameraWithBlack(top,bottom,left,right):
	blocks=[];
	boxImg,blocksL,blocksU=handleTopWithBlack(top);
	boxImg,blocksD,blocksR=handleBottomWithBlack(bottom);
	boxImg,blocksF=handleLeftOrRightWithBlack(left,"left");
	boxImg,blocksB=handleLeftOrRightWithBlack(right,"right");
	blocks.append(blocksU);
	blocks.append(blocksD);
	blocks.append(blocksF);
	blocks.append(blocksB);
	blocks.append(blocksL);
	blocks.append(blocksR);
	return blocks;

def rectKey(rect):
	return cv.contourArea(rect);

def sortByArea(contour):
	x,y,w,h=cv.boundingRect(contour);
	return w*h;

def getDistance(point1,point2):
	dx=point1[0]-point2[0];
	dy=point1[1]-point2[1];
	return sqrt(dx*dx+dy*dy);

def sortByPointX(point):
	return point[0];

def sortByPointY(point):
	return point[1];

#图片透视变换
def imgWarp(img,point1,point2,w,h):
	transform= cv.getPerspectiveTransform(point1,point2);
	return cv.warpPerspective(img,transform,(w,h));

def get2PDis(p1,p2):
    dx=p1[0]-p2[0];
    dy=p1[1]-p2[1];
    return sqrt(dx*dx+dy*dy);

def getDisWithCenterLine(e):
    a=get2PDis(e[1],e[2]);
    b=get2PDis(e[0],e[2]);
    c=get2PDis(e[0],e[1]);
    cosA=(b*b+c*c-a*a)/(2*b*c);
    sinA=abs(sqrt(1-cosA*cosA));
    return b*sinA;
    

#calc center two point(up,down)
def getCenterTwoPoint(img,drawLine=False):
    temp=img.copy();
    h,w=img.shape[0],img.shape[1];
    halfW=w*0.5;
    halfBw=100;
    temp=temp[0:int(h),int(halfW-halfBw):int(halfW+halfBw)];
    #tro gray
    gray=cv.cvtColor(temp,cv.COLOR_BGR2GRAY);
    #canny
    #minV=cv.getTrackbarPos("min","test");
    #maxV=cv.getTrackbarPos("max","test");
    canny=cv.Canny(gray,29,66);
    #cv.imshow("canny",canny);
    #houghLines
    #threold=cv.getTrackbarPos("threold","test");
    #minLength=cv.getTrackbarPos("minLength","test");
    #maxGap=cv.getTrackbarPos("maxGap","test");
    lines=cv.HoughLinesP(canny,1,np.pi/180,20);
    lines=lines[:,0,:];
    #draw lines
    '''for x1,y1,x2,y2 in lines:
        #filter line
        k=abs((y2-y1)*1.0/(x2-x1));
        if k>1 and abs(halfBw-x1)<40:
            cv.line(img,(x1,y1),(x2,y2),(0,0,255),2);'''
    #split lines
    groupPoints=[];
    for x1,y1,x2,y2 in lines:
        #xuan ze chui zhi de xian
        if (x1!=x2 and abs((y2-y1)*1.0/(x2-x1))>1) or (x1==x2 and abs(y1-y2)>1):
            isPut=False;
            for points in groupPoints:
                if abs(points[0][0]-x1)<10:
                    points.append((x1,y1));
                    points.append((x2,y2));
                    isPut=True;
                    break;
            if not isPut:
                points=[];
                points.append((x1,y1));
                points.append((x2,y2));
                groupPoints.append(points);
    #print(len(groupPoints),len(groupPoints[0]),len(groupPoints[1]));
    linesEndPoints=[];
    centerX,centerY=temp.shape[1]*0.5,temp.shape[0]*0.5
    for linePoints in groupPoints:
        arrPoint=np.array(linePoints);
        cos,sin,x,y=cv.fitLine(arrPoint,cv.DIST_L2,0,0.01,0.01);
        if cos!=0:
            k=sin/cos;
            b=y-k*x;
            y1=0;
            x1=int((y1-b)/k);
            y2=h;
            x2=int((y2-b)/k);
            linesEndPoints.append([[x1,y1],[x2,y2],[centerX,centerY]]);
        else:
            linesEndPoints.append([[x,0],[x,h],[centerX,centerY]]);
    #find min dis with centerPoint
    linesEndPoints.sort(key=getDisWithCenterLine);
    #drawLine
    upPoint=linesEndPoints[0][0];
    upPoint[0]=int(upPoint[0]+halfW-halfBw);
    upPoint[1]=int(upPoint[1]);
    downPoint=linesEndPoints[0][1];
    downPoint[0]=int(downPoint[0]+halfW-halfBw);
    downPoint[1]=int(downPoint[1]);
    if drawLine:
        cv.line(img,(upPoint[0],upPoint[1]),(downPoint[0],downPoint[1]),(0,0,255),2);
    #cv.imshow("img",img);
    #cv.waitKey(10);
    #print(linesEndPoints);
    return upPoint,downPoint;

#处理背景为白色的魔方
def handleTopByOne2(top,num):
	topCopy=top.copy();
	#设置检测框
	cx,cy=top.shape[1]//2,top.shape[0]//2;
	x1,y1,x2,y2=cx-boxW_top//2,cy-boxH_top//2,cx+boxW_top//2,cy+boxH_top//2;
	#提取检测框ROI
	boxROI=top[y1:y2,x1:x2];
	#灰度化
	grayROI=cv.cvtColor(boxROI,cv.COLOR_BGR2GRAY);
	#二值化
	#-9 35
	ret,binROI=cv.threshold(grayROI,60,255,cv.THRESH_BINARY);
	#腐蚀操作
	kernel = cv.getStructuringElement(cv.MORPH_RECT,(7,7));
	eroded = cv.erode(binROI,kernel);
	#提取轮廓
	hierarchy,contours,value=cv.findContours(eroded,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)    # 输出为三个参数  
	#draw contours
	#cv.drawContours(boxROI,contours,-1,(0,0,255),2);
	#筛选轮廓提取所有魔方块外接矩形
	#按照面积从小到大
	contours=sorted(contours,key=sortByArea);
	#计算魔方凸包
	hull=cv.convexHull(contours[len(contours)-1], False);
	#绘制凸包点
	#cv.drawContours(boxROI,hull,-1,(0,0,255),2);
	#绘制凸包外接轮廓
	x,y,w,h=cv.boundingRect(hull);
	#cv.rectangle(boxROI, (x,y), (x+w,y+h), (0,0,255), 2);
	#寻找四个顶点(从图片左上开始)
	points=[[],[],[],[]];
	#找左边的
	leftPoints=[];
	for point in hull:
		if fabs(point[0][0]-x)<20:
			leftPoints.append(point[0]);
	#按照Y排序
	leftPoints.sort(key=sortByPointY);
	points[0]=leftPoints[0];
	points[3]=leftPoints[len(leftPoints)-1];
	#找右边的
	rightPoints=[];
	for point in hull:
		if fabs(point[0][0]-(x+w))<20:
			rightPoints.append(point[0]);
	#按照Y排序
	rightPoints.sort(key=sortByPointY);
	points[1]=rightPoints[0];
	points[2]=rightPoints[len(rightPoints)-1];
	#恢复数据
	'''reduce=70;#减少的高度
	points[0][1]=points[0][1]-reduce//2;
	points[1][1]=points[1][1]-reduce//2;
	points[2][1]=points[2][1]+reduce//2;
	points[3][1]=points[3][1]+reduce//2;
	h+=reduce;
	boxROI=topCopy[y+y1-reduce//2:y+h+y1-reduce//2,x+x1:x+x1+w];'''
	#分割成两张照片
	#leftImg=boxROI[y:y+h,x:x+w//2];
	#rightImg=boxROI[y:y+h,x+w//2:x+w];
	#get center two point
	upP,downP=getCenterTwoPoint(boxROI,False);
	centerLineX=int((upP[0]+downP[0])*0.5);
	leftImg=boxROI[y:y+h,x:centerLineX];
	rightImg=boxROI[y:y+h,centerLineX:x+w];
	#cv.imshow("points",boxROI);
	#cv.waitKey(10);
	#input("please:");
	#cv.imshow("leftImg",leftImg);
	#cv.imshow("rightImg",rightImg);
	#左边图透视变换
	lw=leftImg.shape[1];
	point1 = np.array([[points[0][0]-x,points[0][1]-y],[lw,0],[lw,h],[points[3][0]-x,points[3][1]-y]],dtype = "float32");
	point2 = np.array([[0,0],[h,0],[h,h],[0,h]],dtype = "float32")
	leftWrap=imgWarp(leftImg,point1,point2,h,h);
	#右边图透视变换
	rw=leftImg.shape[1];
	point1 = np.array([[0,0],[points[1][0]-x-lw,points[1][1]-y],[points[2][0]-x-lw,points[2][1]-y],[0,h]],dtype = "float32");
	point2 = np.array([[0,0],[h,0],[h,h],[0,h]],dtype = "float32")
	rightWrap=imgWarp(rightImg,point1,point2,h,h);
	#cv.imshow("leftWrap",leftWrap);
	#cv.imshow("rightWrap",rightWrap);
	#绘制几个顶点 
	#for point in points:
	#	cv.circle(boxROI, (point[0], point[1]), 5, (0,255,2), 8);
	#开始图片旋转
	if num==1:
		#分别是L，U
		return imgRoate(leftWrap,-90),rightWrap;
	elif num==2:
		#分别是F,R
		return leftWrap,rightWrap;
	elif num==3:
		#分别是D,B
		return imgRoate(leftWrap,90),imgRoate(rightWrap,-90);
    

'''
for i in range(3):
    print("start:"+str(i+1));
    img3=cv.imread("/home/pi/Desktop/cube/test/"+str(i+1)+".jpg");
    handleTopByOne2(img3,i+1);
    cv.waitKey(20);
    input("please:");
'''
'''
cv.namedWindow("test");
cv.createTrackbar("threold","test",90,200,test);
cv.createTrackbar("minLength","test",40,200,test);
cv.createTrackbar("maxGap","test",30,200,test);
cv.createTrackbar("min","test",33,255,test);
cv.createTrackbar("max","test",126,255,test);
while True:
	img1=cv.imread("/home/pi/Desktop/cube/test/2.jpg");
	handleTopByOne2(img1,2);
'''

#使用一个摄像头处理的情况
#CUBE_TYPE_BLACK类型：直接返回类型
#CUBE_TYPE_WHITE类型:返回面数组
def handleWithOneCamera(img1,img2,img3,cubeType=CUBE_TYPE_BLACK):
	#img1=cv.imread("C:\\Users\\ASUS\\Desktop\\img\\11.jpg");
	#img2=cv.imread("C:\\Users\\ASUS\\Desktop\\img\\2.jpg");
	#img3=cv.imread("C:\\Users\\ASUS\\Desktop\\img\\3.jpg");
	if cubeType==CUBE_TYPE_BLACK:
		blocks=[];
		boxImg,blocksL,blocksU=handleTopByOne(img1,1);
		boxImg,blocksF,blocksR=handleTopByOne(img2,2);
		boxImg,blocksD,blocksB=handleTopByOne(img3,3);
		blocks.append(blocksU);
		blocks.append(blocksD);
		blocks.append(blocksF);
		blocks.append(blocksB);
		blocks.append(blocksL);
		blocks.append(blocksR);
		return blocks;
	elif cubeType==CUBE_TYPE_WHITE:
		imgArray=[];
		imgL,imgU=handleTopByOne2(img1,1);
		imgF,imgR=handleTopByOne2(img2,2);
		imgD,imgB=handleTopByOne2(img3,3);
		imgArray.append(imgU);
		imgArray.append(imgD);
		imgArray.append(imgF);
		imgArray.append(imgB);
		imgArray.append(imgL);
		imgArray.append(imgR);
		return imgArray;
	
'''
cap=cv.VideoCapture(0);

def set(value):
	global cap;
	p=cv.getTrackbarPos("pos","frmae")-20;
	cap.set(cv.CAP_PROP_EXPOSURE, p);

cv.namedWindow("frmae");
#cv.createTrackbar("pos","frmae",10,20,set);
cap.set(cv.CAP_PROP_EXPOSURE, -10);
a=1;
print("当前编号："+str(a));
while cap.isOpened():
	ret,frame=cap.read();
	cv.imshow("frmae",frame);
	word=cv.waitKey(10);
	if word==ord('q'):
		break;
	elif word==ord('s'):
		print("save");
		#cv.imwrite("C:\\Users\\ASUS\\Desktop\\img\\3"+str(a)+".jpg",frame);
		cv.imwrite("C:\\Users\\ASUS\\Desktop\\img\\right.jpg",frame);
	elif word==ord('n'):
		a+=1;
		print("当前编号："+str(a));
'''